/**
 * @author jiangqifan
 * @since 2016-12-22
 */

"use strict";

var session = require('express-session');
var logger = require('log4js').getLogger();

module.exports = function(session_config){

  //init session option
  var sessionOption = {
      store: new session.MemoryStore(),
      name: 'sid.beecode.cn',
      resave: true,
      saveUninitialized: false,
      secret: 'a strong secrect',
      rolling: true,
      cookie: {
        maxAge: 24 * 60 * 60 * 1000
      }
  };

  //read session option from config
  if(session_config){

    if(session_config.store){
      //parse session store config
      if('mongodb' == session_config.store.type){
        // logger.info('use mongodb session store.');
        // var MongoStore = require('connect-mongo')(session);
        // var sesstion_url = session_config.store.url || 'mongodb://localhost/enzyme-session';
        // const mongoose = require('mongoose');
        // const connectionOptions = {
        //   server: { 
        //     poolSize: 5,
        //     reconnectTries: Number.MAX_VALUE,
        //     reconnectInterval:1000,
        //     socketOptions:{
        //       keepAlive: 120000
        //     }
        //   },
        //   replset:{
        //     socketOptions:{
        //       keepAlive: 120000
        //     }
        //   }
        // };
        // mongoose.connect(sesstion_url, connectionOptions);
        // sessionOption.store = new MongoStore({mongooseConnection: mongoose.connection});
        
        // sessionOption.store = new MongoStore({ url: sesstion_url});
      } else if('redis' == session_config.store.type){
        logger.info('use redis session store.');
        var RedisStore = require('connect-redis')(session);
        var redis_url = session_config.store.url || 'redis://localhost';
        sessionOption.store = new RedisStore({url:redis_url});
      } else {
        logger.error('not supported session store type:'+ session_config.store.type+" , will use memory store.");
      }
      //add listener on session store
      sessionOption.store.on('connect',()=>{
        logger.debug('session store connect');
      });
      sessionOption.store.on('disconnect',(e)=>{
        logger.debug('session store disconnect');
      });
      sessionOption.store.on('error',(error)=>{
        logger.error(error);
        logger.error('session store error');
      });
      sessionOption.store.on('close',(error)=>{
        logger.debug(error);
        logger.debug('session store close');
      });
    }

    if(session_config.cookie){
      // maybe it's not a secure method
      sessionOption.cookie = Object.assign(sessionOption.cookie, session_config.cookie);
    }

    sessionOption.name = session_config.name || sessionOption.name;
    sessionOption.secret = session_config.secret || sessionOption.secret;


  }

  logger.info('session options.cookie: '+ JSON.stringify(sessionOption.cookie));
  logger.info('session options.name: '+ sessionOption.name);

  var sessionMiddleware = session(sessionOption);
  sessionMiddleware.__store = sessionOption.store;

  return sessionMiddleware;
}
